package com.hspedu.com.jdbc.preparedstatement_;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author DL5O
 * @version 1.0
 * 演示PreparedStatement使用 DML 语句
 */
public class PreparedStatementDML_ {
    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
        Scanner sc = new Scanner(System.in);
        //让用户输入管理员和密码
        System.out.print("请输入要修改管理员的名字:");
        String admin_name = sc.nextLine();//老韩说明，如果希望看到SQL注入，这里需要使用nextLine
//        System.out.print("请输入要修改管理员的密码:");
//        String admin_pwd = sc.nextLine();//next当接收到空格或者 '就是结束

        Properties properties = new Properties();
        properties.load(new FileReader("src\\jdbc.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        //1.注册驱动
        Class.forName(driver);//建议写上
        //2.得到连接
        Connection connection = DriverManager.getConnection(url, user, password);

        //3.得到PreparedStatement
        //3.1 组织SQL语句, SQL语句的 ? 就相当于占位符
        //插入
        //String sql = "insert into admin values(?,?)";
        //String sql = "update admin set pwd = ? where name = ?";
        String sql = "delete from admin where name = ?";//删除语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, admin_name);

        int rows = preparedStatement.executeUpdate();//进行更新
        System.out.println(rows > 0 ? "执行成功" : "执行失败");

        preparedStatement.close();
        connection.close();
    }
}
